package com.zbzly.reactive.reactiverbac.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbzly.reactive.reactiverbac.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Component
public class JwtWebFilter implements WebFilter {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public @NotNull Mono<Void> filter(@NotNull ServerWebExchange exchange, @NotNull WebFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        boolean match = new AntPathMatcher().match("/login", exchange.getRequest().getPath().value());
        if (StringUtils.hasText(token) && !match) {
            Claims claims = jwtUtil.parseToken(token);
            String username = claims.getSubject();
            exchange.getAttributes().put("username", username);
            return chain.filter(exchange);
        }
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        ObjectMapper mapper = new ObjectMapper();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("error", "登陆过期");
        String body;
        try {
            body = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return exchange.getResponse().writeWith(Mono.just(dataBuffer));
    }

}
